package com.songshuai.webapi.message.aop;

import com.songshuai.webapi.baseapi.enumerations.ResultStatus;
import com.songshuai.webapi.baseapi.exception.BusinessException;
import com.songshuai.webapi.baseapi.pojo.QueryResponse;
import com.songshuai.webapi.common.aop.BaseLogAspect;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;


/**
 * Created by yubo on 2018/12/18
 */
@Aspect
@Component
public class LogAspect extends BaseLogAspect {
  private static Log logger = LogFactory.getLog(LogAspect.class);


  @Pointcut("execution(public * com.songshuai.webapi.message.controller.*.*(..))")
  public void webLog() {
    //切面
  }

  @Around("webLog()")
  public Object arround(ProceedingJoinPoint pjp) throws Throwable {
    // 接收到请求，记录请求内容
    StringBuffer logBuffer = new StringBuffer();
    ServletRequestAttributes attributes =
            (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    // 记录下请求内容

    logBuffer.append("[");
    logBuffer.append("URL=" + request.getRequestURI().toString());
    logBuffer.append(";");
    logBuffer.append(" HTTP_METHOD=" + request.getMethod());
    logBuffer.append(";");
    logBuffer.append(" IP=" + request.getRemoteAddr());
    logBuffer.append(";");
    logBuffer.append(" CLASS_METHOD=" + pjp.getSignature().getDeclaringTypeName() + "."
            + pjp.getSignature().getName());
    logBuffer.append(";");
    logBuffer.append(" ARGS=" + Arrays.toString(pjp.getArgs()));


    // logger.info(logBuffer);
    Long startDate = System.currentTimeMillis();
    // 执行方法
    Object o = null;
    try {
      o = pjp.proceed();
    }
    catch (BusinessException ex){
      o= QueryResponse.setResData(null, ex.getCode(),ex.getMessage());

    }
    catch (Throwable t) {
      t.printStackTrace();
      o=QueryResponse.setResData(null, ResultStatus.FAIL,"系统运行时异常");

      logger.error("系统运行时异常" + t);
    }
    Long endDate = System.currentTimeMillis();
    logBuffer.append(";");
    logBuffer.append(" TIME=" + (endDate - startDate));
    logBuffer.append("]");
    logger.info(logBuffer.toString());
    return o;
  }


  }



